Add custom level
Table of Content
Python has six log levels with each one assigned a specific integer indicating the severity of the log:
- NOTSET=0
- DEBUG=10
- INFO=20
- WARN=30
- ERROR=40
- CRITICAL=50
using setLevel method on logging and handlers we can control/filter the output logging severity
Demo#
custom_level.py
import logging
#create new log level
LOG_LEVEL_CLIENT = 21
logging.CLIENT = LOG_LEVEL_CLIENT
logging.addLevelName(logging.CLIENT, "CLIENT")
#create logger with "mylogger"
logger = logging.getLogger("mylogger")
logger.setLevel(logging.DEBUG)
#create console handler and set level to debug
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
logger.addHandler(handler)
#create formatter
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s -%(message)s")
handler.setFormatter(formatter)
logger.debug("this is debug")
logger.info("this is info")
logger.log(logging.CLIENT, "this is client")
logger.warning("this is warning")
logger.error("this is error")
logger.critical("this is critical")
Result
2022-11-26 06:44:19,616 - mylogger - INFO -this is info
2022-11-26 06:44:19,616 - mylogger - CLIENT -this is client
2022-11-26 06:44:19,616 - mylogger - WARNING -this is warning
2022-11-26 06:44:19,616 - mylogger - ERROR -this is error
2022-11-26 06:44:19,616 - mylogger - CRITICAL -this is critical
setLevel
The above example setLevel method set to severity output to Info
No DEBUG logging is “print”